import datetime
from kubernetes import client, config
from kubernetes.client.rest import ApiException

# 加载k8s集群配置（从 Pod 内部读取配置），创建API客户端
config.load_incluster_config()
api_instance = client.AppsV1Api()

def get_daemonset_command(namespace, name):
  try:
    # 获取现有的 DaemonSet
    daemonset = api_instance.read_namespaced_daemon_set(name, namespace)
    return daemonset.spec.template.spec.containers[0].command
  except ApiException as e:
    print("Exception when calling AppsV1Api->patch_namespaced_daemon_set: %s\n" % e)

def get_daemonset_env(namespace, name):
  try:
    # 获取现有的 DaemonSet
    daemonset = api_instance.read_namespaced_daemon_set(name, namespace)
    return daemonset.spec.template.spec.containers[0].env
  except ApiException as e:
    print("Exception when calling AppsV1Api->patch_namespaced_daemon_set: %s\n" % e)

def set_daemonset_env(namespace, name, env):
  try:
    # 获取现有的 DaemonSet
    daemonset = api_instance.read_namespaced_daemon_set(name, namespace)
    daemonset.spec.template.spec.containers[0].env = env

    # 更新 DaemonSet
    api_response = api_instance.patch_namespaced_daemon_set(name, namespace, daemonset)
    print("DaemonSet restarted. Status='%s'" % str(api_response.status))
  except ApiException as e:
    print("Exception when calling AppsV1Api->patch_namespaced_daemon_set: %s\n" % e)

def set_daemonset_command(namespace, name, command):
  try:
    # 获取现有的 DaemonSet
    daemonset = api_instance.read_namespaced_daemon_set(name, namespace)
    daemonset.spec.template.spec.containers[0].command = command

    # 更新 DaemonSet
    api_response = api_instance.patch_namespaced_daemon_set(name, namespace, daemonset)
    print("DaemonSet restarted. Status='%s'" % str(api_response.status))
  except ApiException as e:
    print("Exception when calling AppsV1Api->patch_namespaced_daemon_set: %s\n" % e)

def restart_daemonset(namespace, name):
  try:
    # 获取现有的 DaemonSet
    daemonset = api_instance.read_namespaced_daemon_set(name, namespace)

    # 修改 DaemonSet 的模板标签，触发滚动更新
    now = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%S")
    daemonset.spec.template.metadata.labels['restartedAt'] = now

    # 更新 DaemonSet
    api_response = api_instance.patch_namespaced_daemon_set(name, namespace, daemonset)
    print("DaemonSet restarted. Status='%s'" % str(api_response.status))
  except ApiException as e:
    print("Exception when calling AppsV1Api->patch_namespaced_daemon_set: %s\n" % e)
